//
//  SortView.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/4/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SnapKit




class SortViewModel {
    struct SortItem: Equatable {
        var name: String
        var id: Int
    }
    
    var data: [SortItem] = [
        SortItem(name: "Дате размещения", id: 1),
        SortItem(name: "Возрастанию цены", id: 2),
        SortItem(name: "Убыванию цены", id: 3),
        SortItem(name: "Году: новее", id: 4),
        SortItem(name: "Году: старше", id: 5),
        SortItem(name: "По цене и году", id: 6),
        SortItem(name: "Пробегу", id: 7)
    ]
    var currentSelected: SortItem?
}


class SortItemCell: UITableViewCell {
    
    // MARK: - Outlets
    
    private lazy var titleLbl: UILabel = {
        let lbl = UILabel ()
        lbl.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        lbl.textAlignment = .left
        lbl.textColor = .darkBlueColor
        return lbl
    }()
    private lazy var circleView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        view.layer.borderWidth = 1.0
        view.layer.borderColor = UIColor.greyBlue.cgColor
        view.layer.cornerRadius = 10.0
        return view
    }()
    private lazy var iconImg: UIImageView = {
        let img = UIImageView()
        img.contentMode = .scaleAspectFit
        return img
    }()
    
    // MARK: - Props
    
    var data: SortViewModel.SortItem! {
        didSet {
            self.titleLbl.text = data.name
        }
    }
    
    var isClicked: Bool = false {
        didSet {
            if isClicked {
                self.setSelected()
            } else {
                self.setDeselected()
            }
        }
    }
    
    // MARK: - Actions
    
    private func setSelected () {
        self.contentView.backgroundColor = .whiteBlueColor
        self.circleView.layer.borderWidth = 0.0
        self.circleView.backgroundColor = .darkBlueColor
        self.iconImg.image = UIImage(named: "correct")
    }
    private func setDeselected () {
        self.contentView.backgroundColor = .clear
        self.circleView.layer.borderWidth = 1.0
        self.circleView.backgroundColor = .clear
        self.iconImg.image = nil
    }
    
    // MARK: - Init
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.addView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func addView () {
        self.contentView.addSubview(titleLbl)
        self.contentView.addSubview(circleView)
        circleView.addSubview(iconImg)
        self.addConstraints()
    }
    
    private func addConstraints () {
        circleView.snp.makeConstraints { (make) in
            make.width.height.equalTo(20)
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().offset(-16)
        }
        iconImg.snp.makeConstraints { (make) in
            make.width.equalTo(12)
            make.height.equalTo(9)
            make.centerX.centerY.equalToSuperview()
        }
        
        titleLbl.snp.makeConstraints { (make) in
            make.leading.equalToSuperview().inset(16)
            make.trailing.equalTo(circleView.snp.leading).offset(16)
            make.centerY.equalToSuperview()
        }
    }
}


class SortView: UIView {

    
    // MARK: - Outlets
    
    private lazy var titleLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 20, weight: .bold)
        lbl.textColor = .black
        lbl.textAlignment = .left
        lbl.sizeToFit()
        return lbl
    }()
    
    private lazy var closeBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "dismiss"), for: .normal)
        return btn
    }()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.showsVerticalScrollIndicator = false
        tableView.tableFooterView = UIView()
        tableView.backgroundColor = .white
        tableView.register(SortItemCell.self, forCellReuseIdentifier: "sortItemCell")
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    private lazy var submitBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("Применть", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.layer.cornerRadius = 15
        btn.clipsToBounds = true
        btn.backgroundColor = .blueColor
        return btn
    }()
    
    
    // MARK: - Props
    
    private var sortModel = SortViewModel()
    weak var parentVC: ResultsViewController!
    
    // MARK: - Actions
    
    @objc private func onCancel (sender: UIButton) {
        parentVC.hideShowView()
    }
    
    @objc private func onSubmit (sender: UIButton) {
        if let currentSelected = sortModel.currentSelected {
            parentVC.setSort(sortId: currentSelected.id)
        }
        parentVC.hideShowView()
    }
    
    // MARK: - Init
    
    init () {
        super.init(frame: .zero)
        self.titleLbl.text = "Сортировать по"
        self.addView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


extension SortView {
    private func addView () {
        self.backgroundColor = .white
        self.layer.shadowOffset = CGSize(width: 0, height: -20)
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowRadius = 40
        self.layer.shadowOpacity = 0.15
        
        self.addSubview(closeBtn)
        self.addSubview(titleLbl)
        self.addSubview(tableView)
        self.addSubview(submitBtn)
        closeBtn.addTarget(self, action: #selector(onCancel(sender:)), for: .touchUpInside)
        submitBtn.addTarget(self, action: #selector(onSubmit(sender:)), for: .touchUpInside)
        self.addConstraints()
    }
    
    private func addConstraints () {
        self.closeBtn.snp.makeConstraints { (make) in
            make.top.equalToSuperview().inset(28)
            make.width.height.equalTo(16)
            make.trailing.equalToSuperview().offset(-16)
        }
        self.titleLbl.snp.makeConstraints { (make) in
            make.leading.equalToSuperview().offset(16)
            make.centerY.equalTo(closeBtn)
        }
        self.submitBtn.snp.makeConstraints { (make) in
            make.leading.trailing.bottom.equalToSuperview().inset(16)
            make.height.equalTo(44)
        }
        self.tableView.snp.makeConstraints { (make) in
            make.bottom.equalTo(submitBtn.snp.top).offset(-12)
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(titleLbl.snp.bottom).offset(25)
        }
    }
}

extension SortView: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var rowsNeedToBeUpdated:[IndexPath] = [indexPath]
        if let _currentSelected = sortModel.currentSelected {
            let index = sortModel.data.firstIndex(of: _currentSelected)
             rowsNeedToBeUpdated.append(IndexPath(item: index!, section: 0))
        }
        sortModel.currentSelected = sortModel.data[indexPath.row]
        tableView.reloadRows(at: rowsNeedToBeUpdated, with: .top)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sortModel.data.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "sortItemCell") as! SortItemCell
        cell.data = sortModel.data[indexPath.row]
        cell.isClicked = sortModel.currentSelected == sortModel.data[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 48.0
    }
}
